package com.atg.spring_ai.controller;


import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisModel;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisPrompt;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisResponse;
import jakarta.annotation.PreDestroy;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.CountDownLatch;

/*
author: atg
time: 2025/6/13 15:42
*/

// 文字生成语音
@RestController
@RequestMapping("/ai/tts")
public class DashScopeTTsController implements ApplicationRunner {

    private final SpeechSynthesisModel speechSynthesisModel;

    // 文件夹路径
    private static final String FILE_PATH = "src/main/resources/gen_tts";

    public DashScopeTTsController(SpeechSynthesisModel speechSynthesisModel) {
        this.speechSynthesisModel = speechSynthesisModel;
    }

    @GetMapping("/text")
    public void textToSpeech(@RequestParam String text) {

        SpeechSynthesisPrompt textPrompt = new SpeechSynthesisPrompt(text);
        SpeechSynthesisResponse response = speechSynthesisModel.call(textPrompt);

        // 判断文件夹在不在
        File file = new File(FILE_PATH + "/output.mp3");

        try(FileOutputStream fileOutputStream = new FileOutputStream(file)){
            ByteBuffer TtsAudio = response.getResult().getOutput().getAudio();
            fileOutputStream.write(TtsAudio.array());


        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }

    }



    @Override
    public void run(ApplicationArguments args) {

        File file = new File(FILE_PATH);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    @PreDestroy
    public void destroy() throws IOException {
        // 删除默认的示例路径
        String example_file_path = "src/main/resources/gen_tts";
        FileUtils.deleteDirectory(new File(example_file_path));
    }
}
